package com.zt.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zt.common.Result;
import com.zt.pojo.Users;
import com.zt.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/api")
public class UserController {
    @Autowired
    private UsersService usersService;
    @PostMapping("/login")
    public Result login(@RequestBody Users users){
        Users one = usersService.getOne(new QueryWrapper<Users>().lambda().eq(Users::getUsername, users.getUsername()));
        if (one!=null){
            if (one.getPassword().equals(users.getPassword())){
                return Result.OK(one);
            }
        }
        return Result.ERROR("登录失败");

    }
    /**
     * 添加用户
     * @param users
     * @return
     */
    @PostMapping("/users")
    public Result addUser(@RequestBody Users users){
        Users one = usersService.getOne(new QueryWrapper<Users>().lambda().eq(Users::getUsername, users.getUsername()));
        if (one!=null){
            return Result.ERROR("用户已存在");
        }
        users.setCreatedAt(new Date());
        users.setUpdatedAt(new Date());
        boolean save = usersService.save(users);
        return save?Result.OK():Result.ERROR("操作失败");
    }

    /**
     * 获取用户列表
     * @return
     */
    @GetMapping("/users")
    public Result getUsersList(){
        return Result.OK(usersService.list());
    }

    /**
     * 更新用户信息
     * @param users
     * @param id
     * @return
     */
    @PutMapping("/users/{id}")
    public Result updateUsers(@RequestBody Users users,@PathVariable Integer id){
        Users byId = usersService.getById(id);
        boolean update=false;
        if (byId!=null){
            update=usersService.updateById(users);
        }
        return update?Result.OK():Result.ERROR();
    }

    @DeleteMapping("/users/{id}")
    public Result delete(@PathVariable Integer id){
        Users byId = usersService.getById(id);
        boolean delete=false;
        if (byId!=null){
            delete=usersService.removeById(byId.getId());
        }
        return delete?Result.OK():Result.ERROR();
    }
}
